package com.lagou.controller;

import com.lagou.pojo.Article;
import com.lagou.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class ArticleController {

    @Autowired
    ArticleService articleService;


    @RequestMapping("/")
    public String index() {
        return "redirect:/index";
    }

    @RequestMapping("/index")
    String findAllArticle1(Model model,@RequestParam(required = false,defaultValue = "0") int pageNum){
        // 每页显示两条记录
        Page<Article> pages = articleService.pagingFindArticle(pageNum, 2);
        List<Article> articles = pages.toList();
        model.addAttribute("articleList",articles);
        // 总页数
        int totalPages = pages.getTotalPages();
        // 当前所在页索引
        int currentPage = pages.getNumber();
        // 将末页的索引号及当前索引号添加到模型属性值中
        model.addAttribute("lastPage",totalPages-1);
        model.addAttribute("currentPage",currentPage);

        // 如果当前页为第一页或最后一页则分别返回-1和0，其页面为1
        int pageFlag = 1;
        if(currentPage==totalPages-1){
            pageFlag = 0;
        }else if(currentPage == 0){
            pageFlag = -1;
        }
        model.addAttribute("pageFlag",pageFlag);
        return "index";
    }
}
